const axios = require('axios');
const log4js = require('log4js');
const {Util, Type} = require('dob_common');

class Client {
  constructor() {
    this.$timeout = 5000;
    this.$retryTime = 5;
    this.$retryDelay = 1000;
    this.$client = null;
  }

  get timeout() {
    return this.$timeout;
  }

  set timeout(value) {
    if(Type.isInteger(value) === true && value > 0) {
      this.$timeout = value;
    }
  }

  get retryTime() {
    return this.$retryTime;
  }

  set retryTime(value) {
    if(Type.isInteger(value) === true && value > 0) {
      this.$retryTime = value;
    }
  }

  get retryDelay() {
    return this.$retryDelay;
  }

  set retryDelay(value) {
    if(Type.isInteger(value) === true && value > 0) {
      this.$retryDelay = value;
    }
  }

  get logger() {
    return log4js.getLogger('dob_http::Client');
  }

  createClient(config) {
    if(this.$client === null) {
      this.$client = axios.create(config);
    }
  }

  async request(config) {
    if(this.$client !== null) {
      for(let i = 0; i < this.retryTime; i++) {
        try {
          let response = await Promise.race(
            [
              this.$client.request(config),
              (async () => {
                await Util.sleep(this.timeout);
                throw new Error();
              })()
            ]
          );

          return response;
        }
        catch(error) {
          await Util.sleep(this.retryDelay);
        }
      }

      throw new Error('http timeout');
    }
  }
}

module.exports = Client;